#!/bin/bash
# 安装Redis及配置服务

# 引入公共配置
source ./common.sh

# 确保应用目录存在
app_home

function install_redis() {
    local appname="redis-${Version}.tar.gz"
    local redisbin="/usr/local/redis/bin/*"
    local usrbin="/usr/local/bin/"
    
    if [ ! -e "${APPS_HOME}/${appname}" ];then
        echo "正在下载Redis ${Version}..."
        wget -P ${APPS_HOME} ${REDIS_NAME}${Version}.tar.gz
        if [ $? -ne 0 ]; then
            error_exit "Redis下载失败"
        fi
    fi
    
    tar xf ${APPS_HOME}/redis-${Version}.tar.gz -C ${Basedir}/
    
    # 创建redis用户
    if ! id -u redis >/dev/null 2>&1; then
        groupadd redis
        useradd -r -g redis -s /sbin/nologin redis
    fi
    
    rm -rf /usr/local/bin/redis*
    rm -rf /usr/local/redis
    cd ${Basedir}/redis-${Version} && make install PREFIX=/usr/local/redis
    cp ${Basedir}/redis-${Version}/redis.conf /usr/local/redis/
    ln -s ${redisbin} ${usrbin}
    chown -R redis:redis /usr/local/redis
}

function configure_redis_service() {
    if [[ ! -f "${REDIS_SERVICE}" ]];then
        echo "创建redis服务文件"
        cat > ${REDIS_SERVICE} <<EOF
[Unit]
Description=Redis
After=redis.target

[Service]
Type=simple
User=redis
Group=redis
ExecStart=/usr/local/bin/redis-server /usr/local/redis/redis.conf

Restart=always
RestartSec=1
StartLimitInterval=0
ProtectHome=yes
NoNewPrivileges=yes

[Install]
WantedBy=multi-user.target
EOF

        systemctl daemon-reload
        systemctl start redis
        systemctl enable redis
        
        redis-cli -v
        if [ $? -eq 0 ];then
            success_msg "redis ${Version} 安装完成"
        fi
    else
        echo "redis服务文件已存在"
    fi
}

echo "开始安装Redis..."

read -p "输入需要的redis版本(默认7.0.0): " Version
if [ -z "${Version}" ];then
    Version="7.0.0"
    echo "使用默认版本: $Version"
fi

install_redis
configure_redis_service
